<?php

    /**
    * This is the model class for table "bill".
    *
    * The followings are the available columns in table 'bill':
    * @property string $id
    * @property string $customer_id
    * @property string $customer_guest_name
    * @property string $customer_guest_address
    * @property string $type
    * @property integer $use_service_laundry
    * @property integer $use_service_dry
    * @property integer $use_service_iron
    * @property integer $use_service_laundry_dry
    * @property string $price
    * @property string $used_point
    * @property integer $bonus_percent
    * @property string $bonus_point
    * @property string $pay_price
    * @property string $pay_price_laundry_dry
    * @property string $customer_point_before
    * @property string $customer_point_after
    * @property string $info
    * @property string $branch_id
    * @property string $manager_id
    * @property string $created
    * @property string $status_pay
    * @property string $status_do
    * @property string $status_return
    * @property string $status
    *
    * The followings are the available model relations:
    * @property Branch $branch
    * @property Customer $customer
    * @property Manager $manager
    * @property ManagerUpdateBill[] $managerUpdateBills
    */
    class Bill extends Model
    {
        public $customer_phone;
        public $customer_name;

        public $manager_phone;
        public $manager_name;
        
        public $send_sms = 1;

        /**
        * Returns the static model of the specified AR class.
        * @param string $className active record class name.
        * @return Bill the static model class
        */
        public static function model($className=__CLASS__)
        {
            return parent::model($className);
        }

        /**
        * @return string the associated database table name
        */
        public function tableName()
        {
            return 'bill';
        }

        /**
        * @return array validation rules for model attributes.
        */
        public function rules()
        {
            // NOTE: you should only define rules for those attributes that
            // will receive user inputs.
            return array(
                array('customer_id, type, price, bonus_percent, bonus_point, pay_price, info, branch_id, manager_id, created, status', 'required'),
                array('use_service_laundry, use_service_dry, use_service_iron, use_service_laundry_dry, bonus_percent', 'numerical', 'integerOnly'=>true),
                array('customer_id, price, used_point, bonus_point, pay_price, pay_price_laundry_dry, customer_point_before, customer_point_after, branch_id, manager_id', 'length', 'max'=>10),
                array('customer_phone, customer_name, manager_phone, manager_name, send_sms', 'length', 'max'=>50),

                array('code', 'match', 'pattern' => '/^[\d]{9,}$/i', 'message' => 'Mã đơn hàng không hợp lệ'),
                array('status', 'checkStatus', 'on' => 'update'),

                array('status_pay, status_do, status_return, status', 'match', 'pattern' => '/^(PAID|UNPAID|PENDING|PROCESSING|COMPLETED|YES|NO|CANCEL)$/', 'message' => 'Trạng thái đơn hàng không hợp lệ'),
                // The following rule is used by search().
                // Please remove those attributes that should not be searched.
                array('id, customer_id, customer_guest_name, customer_guest_address, type, use_service_laundry, use_service_dry, use_service_iron, use_service_laundry_dry, price, used_point, bonus_percent, bonus_point, pay_price, customer_point_before, customer_point_after, info, branch_id, manager_id, created, status', 'safe', 'on'=>'search'),
            );
        }

        public function checkStatus($attribute, $params)
        {
            $post = $_POST['Bill'];
            if($post['status'] == 'COMPLETED' && ($post['status_pay'] != 'PAID' || $post['status_do'] != 'COMPLETED' || $post['status_return'] != 'YES')){
                $this->addError('status', 'Đơn hàng chỉ có thể cập nhật <b>Đã xong</b> khi <b>đã thanh toán</b>, <b>đã giặt xong</b> và <b>đã trả đồ</b>.'); 
                return;   
            }

            if($post['status_do'] == 'PROCESSING' && $post['status_return'] == 'YES'){
                $this->addError('status', 'Đơn hàng <b>Đang giặt</b> thì không thể chọn <b>đã trả đồ</b>.'); 
                return;   
            }
        }


        /**
        * @return array relational rules.
        */
        public function relations()
        {
            // NOTE: you may need to adjust the relation name and the related
            // class name for the relations automatically generated below.
            return array(
                'branch' => array(self::BELONGS_TO, 'Branch', 'branch_id'),
                'customer' => array(self::BELONGS_TO, 'Customer', 'customer_id'),
                'manager' => array(self::BELONGS_TO, 'Manager', 'manager_id'),
                'managerUpdateBills' => array(self::HAS_MANY, 'ManagerUpdateBill', 'bill_id'),
            );
        }

        /**
        * @return array customized attribute labels (name=>label)
        */
        public function attributeLabels()
        {
            return array(
                'id' => 'ID',
                'code' => Yii::t('app', 'Mã'),
                'customer_id' => Yii::t('app', 'Khách hàng'),
                'customer_phone' => Yii::t('app', 'SĐT khách hàng'),
                'customer_name' => Yii::t('app', 'Tên khách hàng'),
                'customer_guest_name' => Yii::t('app', 'Tên khách vãng lai'),
                'customer_guest_address' => Yii::t('app', 'Địa chỉ khách vãng lai'),
                'type' => Yii::t('app', 'Loại dơn hàng'),
                'use_service_laundry' => Yii::t('app', 'Giặt ướt'),
                'use_service_dry' => Yii::t('app', 'Sấy khô'),
                'use_service_iron' => Yii::t('app', 'Là hơi'),
                'use_service_laundry_dry' => Yii::t('app', 'Giặt khô'),
                'price' => Yii::t('app', 'Tiền đơn hàng'),
                'used_point' => Yii::t('app', 'Sử dụng điểm'),
                'bonus_percent' => Yii::t('app', '% thưởng'),
                'bonus_point' => Yii::t('app', 'Điểm thưởng'),
                'pay_price' => Yii::t('app', 'Tiền thanh toán'),
                'customer_point_before' => Yii::t('app', 'Điểm trước đơn hàng'),
                'customer_point_after' => Yii::t('app', 'Điểm sau đơn hàng'),
                'info' => Yii::t('app', 'Thông tin đơn hàng'),
                'branch_id' => Yii::t('app', 'Chi nhánh'),
                'manager_id' => Yii::t('app', 'Nhân viên'),
                'manager_phone' => Yii::t('app', 'Nhân viên'),
                'created' => Yii::t('app', 'Thời gian'),

                'status_pay' => Yii::t('app', 'Thanh toán'),
                'status_do' => Yii::t('app', 'Giặt'),
                'status_return' => Yii::t('app', 'Trả đồ'),
                'status' => Yii::t('app', 'Đơn hàng'),
            );
        }

        public function afterSave(){
            Yii::app()->db->createCommand("UPDATE customer SET bill_count = (SELECT COUNT(*) FROM bill WHERE customer_id = customer.id) WHERE id = {$this->id}")->execute();
            return parent::afterSave();
        }     

        public function getLabelStyle($key){
            if(in_array($key, array('PAID', 'COMPLETED', 'YES')))   return 'success'; 
            if(in_array($key, array('UNPAID', 'NO', 'CANCEL')))   return 'inverse'; 
            if(in_array($key, array('PENDING')))   return 'important'; 
            if(in_array($key, array('PROCESSING')))   return 'warning'; 

        }


        public function getStatusPayData(){
            return array(
                'PAID' => Yii::t('app', 'Đã thanh toán'),
                'UNPAID' => Yii::t('app', 'Chưa thanh toán'),
            );
        }
        public function getStatusPayLabel($status_pay = null){
            $status_pay = $status_pay ? $status_pay : $this->status_pay; 
            return $this->statusPayData[$status_pay]; 
        }

        public function getTypeData(){
            return array(
                'PACKAGE' => Yii::t('app', 'Theo lượt'),
                'ITEM' => Yii::t('app', 'Theo chiếc'),
            );
        }
        public function getTypeLabel($type = null){
            $typeData = $this->getTypeData();
            $type = $type ? $type : $this->type;
            return $typeData[$type]; 
        }

        public function getStatusDoData(){
            return array(
                'PENDING' => Yii::t('app', 'Chờ giặt'),
                'PROCESSING' => Yii::t('app', 'Đang giặt'),
                'COMPLETED' => Yii::t('app', 'Đã giặt xong'),
            );
        }
        public function getStatusDoLabel($status_do = null){
            $status_do = $status_do ? $status_do : $this->status_do;
            return $this->statusDoData[$status_do]; 
        }

        public function getStatusReturnData(){
            return array(
                'YES' => Yii::t('app', 'Đã trả đồ'),
                'NO' => Yii::t('app', 'Chưa trả đồ'),
            );
        }
        public function getStatusReturnLabel($status_return = null){
            $status_return = $status_return ? $status_return : $this->status_return;
            return $this->statusReturnData[$status_return]; 
        }

        public function getStatusData(){
            return array(
                'PROCESSING' => Yii::t('app', 'Đang thực hiện'),
                'CANCEL' => Yii::t('app', 'Hủy'),
                'COMPLETED' => Yii::t('app', 'Đã xong'),
            );
        }
        public function getStatusLabel($status = null){
            $status = $status ? $status : $this->status;
            return $this->statusData[$status]; 
        }

        public function getStatusOptionsData($statusTypeData){
            $data = array();
            foreach(array_keys($statusTypeData) as $key){
                $data[$key] = array('class'=> $this->getLabelStyle($key).' bold');
            }
            return $data;
        }



        public function getAdminUrl($action = 'update', $code = NULL){
            return Yii::app()->createAbsoluteUrl('/admin/bill/'.$action, array('code' => $code ? $code : $this->code));
        }
        public function getUrl($action = 'view', $code = NULL){
            return Yii::app()->createAbsoluteUrl('/web/bill/'.$action, array('code' => $code ? $code : $this->code, 'lang'  => $this->lang));
        }

        public function getPrintUrl(){
            return Yii::app()->createAbsoluteUrl('/web/bill/viewPrint', array(
                'code'=>$this->code,
                'lang'  => $this->lang
            ));
        }
        public function getIndexUrl(){
            return Yii::app()->createAbsoluteUrl('web/bill/index', array(
                'lang'  => $this->lang
            ));
        }
        public function getCustomerUrl(){
            return Yii::app()->createAbsoluteUrl('bill/index', array('phone' => $this->customer->phone));
        }



        public function getIsRound(){
            return is_float(($this->pay_price_laundry_dry * $this->bonus_percent/100));
        }
        public function getPayPriceVND(){
            return Yii::app()->numberFormatter->formatDecimal($this->pay_price*1000);
        }
        public function getCreatedTime(){
            return Yii::app()->dateFormatter->formatDateTime($this->created, 'short', 'short');
        }
        public function getCompletedTime(){
            return Yii::app()->dateFormatter->formatDateTime($this->completed, 'short', 'short');
        }
        public function getPriceLabel(){
            return $this->used_point ? "{$this->pay_price}k = ({$this->price} - {$this->used_point})k" : $this->price.'k';
        }
        

        public function getCustomerName(){
            if($this->customer_id == 1){
                return $this->customer_guest_name;
            }else{
                return $this->customer->name." (".$this->customer->phone.")"; 
            }
        }

        public function getCustomerNameOnly(){
            if($this->customer_id == 1){
                return $this->customer_guest_name;
            }else{
                return $this->customer->name; 
            }
        }
        public function getNextCode(){
            $dateTime = MyDateTime::getCurrentTime('now', false);
            $dateStr = $dateTime->format('ymd');

            $lastBill = Bill::model()->find(array('order' => 'id DESC'));
            $lastBillNumber = 0;
            if($lastBill){
                if(strpos($lastBill->code, $dateStr) !== false){
                    $lastBillNumber = str_replace($dateStr, '', $lastBill->code);    
                }
            }
            $billCode = $dateStr.sprintf('%03d', ($lastBillNumber + 1));
            return $billCode;
        }
        
        public function getListItemHtml(){
            $info = json_decode($this->info, true);

            $html = NULL;
            if($info){
                Item::model()->formatInfo($info);
                $html = "<ul style='margin: 0 -20px;'>";
                foreach($info['items'] as $item){
                    $html .= "<li>".$item['name']."</li>";
                }
                $html .= "</ul>";
            }
            return $html;
            
        }
}